package com.scale.service.voice.controller;

import com.example.common.result.Result;
import com.scale.service.voice.service.VoiceTaskWebSocketHandler;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket连接管理控制器
 * @author crp
 * @since 2025-09-28
 */
@RestController
@RequestMapping("/api/websocket")
@Tag(name = "WebSocket管理", description = "WebSocket连接状态管理接口")
public class WebSocketController {
    
    @Autowired
    private VoiceTaskWebSocketHandler webSocketHandler;
    
    @Value("${server.port:8080}")
    private String serverPort;
    
    /**
     * 检查用户WebSocket连接状态
     */
    @GetMapping("/status/{userId}")
    @Operation(summary = "检查用户连接状态", description = "检查指定用户的WebSocket连接状态")
    public Result<Map<String, Object>> checkStatus(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId) {
        
        Map<String, Object> status = new HashMap<>();
        status.put("userId", userId);
        status.put("connected", webSocketHandler.hasActiveUserSession(userId));
        status.put("sessionInfo", webSocketHandler.getUserSessionInfo(userId));
        status.put("totalConnections", webSocketHandler.getAllActiveUserSessions().size());
        status.put("timestamp", System.currentTimeMillis());
        
        return Result.success(status);
    }
    
    /**
     * 获取用户WebSocket连接URL
     */
    @GetMapping("/url/{userId}")
    @Operation(summary = "获取连接URL", description = "获取指定用户的WebSocket连接URL")
    public Result<Map<String, Object>> getUrl(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId) {
        
        Map<String, Object> urlInfo = new HashMap<>();
        urlInfo.put("userId", userId);
        urlInfo.put("wsUrl", "ws://localhost:" + serverPort + "/ws/voice-task/user/" + userId);
        urlInfo.put("protocol", "WebSocket");
        urlInfo.put("endpoint", "/ws/voice-task/user/{userId}");
        urlInfo.put("timestamp", System.currentTimeMillis());
        
        return Result.success(urlInfo);
    }
    
    /**
     * 获取所有活跃的WebSocket连接
     */
    @GetMapping("/connections")
    @Operation(summary = "获取所有连接", description = "获取当前所有活跃的WebSocket连接信息")
    public Result<Map<String, Object>> getAllConnections() {
        
        Map<String, Object> connections = new HashMap<>();
        connections.put("activeUsers", webSocketHandler.getAllActiveUserSessions().keySet());
        connections.put("totalConnections", webSocketHandler.getAllActiveUserSessions().size());
        connections.put("timestamp", System.currentTimeMillis());
        
        return Result.success(connections);
    }
    
    /**
     * 强制断开用户连接（管理员功能）
     */
    @PostMapping("/disconnect/{userId}")
    @Operation(summary = "断开用户连接", description = "强制断开指定用户的WebSocket连接")
    public Result<String> disconnectUser(
            @Parameter(description = "用户ID", required = true) @PathVariable String userId) {
        
        boolean success = webSocketHandler.disconnectUser(userId);
        if (success) {
            return Result.success("用户连接已断开");
        } else {
            return Result.error("用户未连接或断开失败");
        }
    }
}